package com.doform.android.xianggucheng.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-15.
 * GitHub：https://github.com/cxydxpx
 */

public abstract class BaseFragment extends Fragment implements View.OnClickListener {

    private View contentView;
    private SparseArray<View> mViews;
    private boolean isInitView = false;
    public Context mContext;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

//        Logger.v("onCreateView  : "+this);
        mViews = new SparseArray<>();
        contentView = inflater.inflate(getLayoutResId(), container, false);
        mContext = getActivity();
        ButterKnife.bind(this, contentView);

        init();
        initViews();

        isInitView = true;
        return contentView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    /**
     * 懒加载
     */
    private void lazyLoad() {
//        if (!isInitView) {
//            如果不是初始化view 不可见的  不是第一次加载
//            return;
//        }
        initData();
        initListener();
//        设置已经不是第一次加载
        isInitView = false;
    }

    protected void initListener() {}

    protected abstract int getLayoutResId();

    protected void init() {}

    protected void initViews() {}

    protected void initData() {}

    public <E extends View> E findView(int viewId) {
        if (contentView != null) {
            E view = (E) mViews.get(viewId);
            if (view == null) {
                view = (E) contentView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return view;
        }

        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        showView();
    }

    protected void showView() {
    }

    @Override
    public void onStart() {
        super.onStart();
        updateData();
    }

    protected void updateData() {
    }

    @Override
    public void onClick(View v) {
        processClick(v);
    }

    protected void processClick(View v) {
    }

}
